package com.qf.business.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qf.business.auth.service.IAuthService;
import com.qf.business.user.feign.StuFeign;
import com.qf.commons.base.result.R;
import com.qf.commons.base.user.BaseUser;
import com.qf.data.auth.vo.input.AuthLoginVo;
import com.qf.data.user.entity.Student;
import com.qf.data.user.vo.input.StuLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * author Ken
 * create_time 2022/12/2
 */
@Service("authService1")
@Slf4j
public class StudentAutServiceImpl implements IAuthService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.appsecret}")
    private String appSecret;

    @Autowired
    private StuFeign stuFeign;

    @Override
    public BaseUser login(AuthLoginVo loginVo) {
        log.debug("[student log] 学生端登录 - {}", loginVo);

        //根据临时凭证获取用户sessionid相关信息（校验客户端是否为正常的小程序）
        String json = restTemplate.getForObject("https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + loginVo.getWechatCode() + "&grant_type=authorization_code", String.class);
        log.debug("[wechat login] 微信登录的校验结果 - {}", json);
        JSONObject jsonObject = JSON.parseObject(json);

        //调用用户服务，获取微信小程序的用户对象（第一次获取时，会自动保存）
        StuLoginVo stuLoginVo = new StuLoginVo();
        stuLoginVo.setOpenid(jsonObject.getString("openid"));
        stuLoginVo.setSessionKey(jsonObject.getString("session_key"));
        stuLoginVo.setHeader(loginVo.getHeader());
        stuLoginVo.setNickName(loginVo.getNickName());
        R<Student> result = stuFeign.queryStu(stuLoginVo);
        return result.getData();
    }
}
